Ext.define('framenet.view.frameGrid', {
	extend: 'Ext.grid.Panel',
	alias: 'widget.frameGrid',
	comboFieldSelected: null,
	triggerFieldValue: null,
	rowEditing: null,
	cellEditing: null,

    constructor: function(cfg) {
        var me = this;
        cfg = cfg || {};    

        var columnModel = null;
        var columnsAux = null;
        if (cfg.columnModel)	{
        	columnModel = Ext.create(cfg.columnModel);

            // set array of fields to combo
            cfg.comboFields = new Array();
            for (var i=0; i<columnModel.columns.length; i++)	{
            	cfg.comboFields[i] = new Array(2);
            	cfg.comboFields[i][0] = columnModel.columns[i].dataIndex;
            	cfg.comboFields[i][1] = columnModel.columns[i].text;
            }        
            
            // add delet and edit action
        	var itemsActionColumn = Array();
        	if (cfg.editRow)	{
            	itemsActionColumn.push({
                    icon: 'images/table_edit.png',  // Use a URL in the icon config
                    tooltip: 'Edit',
                    hidden: true,
                    handler: function(grid, rowIndex, colIndex) {
                        var rec = me.getStore().getAt(rowIndex);
                        rowEditing.startEdit(rec, 0);
                    }
                });
        	}
        	
        	if (cfg.deleteRow)	{
            	itemsActionColumn.push({
                    icon: 'images/deletex.png',
                    tooltip: 'Delete',
                    handler: function(grid, rowIndex, colIndex) {
                        var rec = me.getStore().getAt(rowIndex);                        
                        me.store.remove(rec);
			     		me.store.sync();
                    }                
                });
        	}
        	
    		columnsAux = columnModel.columns.slice();

        	if (itemsActionColumn.length > 0) {
        		columnsAux[columnsAux.length] = {
                        xtype:'actioncolumn', 
                        width: itemsActionColumn.length * 20,
                        columnWidth: 20,
                        items: itemsActionColumn
                    };
        	}
        }
        
        
        var tbaritems = Array();

        if (cfg.showSearcher)	{
        	tbaritems.push({
        				xtype: 'panel',
        				layout: {
        				    type: 'hbox',
        				    align: 'stretch'
        				},
        				border: false,
        				items: [{            	
        	   		    			xtype: 'triggerfield',
        	   		    			emptyText: 'Filter...',
        	   		    			flex: 1,
        	   		    			//trigger1Cls: Ext.baseCSSPrefix + 'form-clear-trigger',
        	   		    			trigger1Cls: Ext.baseCSSPrefix + 'form-search-trigger',
        	   		    			listeners: {
        	   		    				specialKey: function(field, el)	{
        	   		    					if (el.getKey() == Ext.EventObject.ENTER)	{
        	   		    						triggerFieldValue = this.value;
        	   		    						me.search();
        	   		    				}
        	   		    			},
        	   		    			blur: function()	{
        	   		    				triggerFieldValue = this.value;
        	   		    			}
        	   		
        	   		    			},
        	   		    			onTriggerClick: function() {
        	   		    				triggerFieldValue = this.value;
        	   		    				me.search();
        	   		    			}
        	   		    		},
        	   		    		{
        	   		    			xtype: 'combo',
        	   		    			store: new Ext.data.SimpleStore({
        	   		    				fields: ['nameField', 'descField'],
        	   		    				data: cfg.comboFields 
        	   		    			}),
        	   		        	    valueField: 'nameField',
        	   		        	    displayField: 'descField',
        	   		        	    typeAhead: true,
        	   		        	    mode: 'local',
        	   		        	    triggerAction: 'all',
        	   		        	    emptyText: 'Choose field...',
        	   		        	    selectOnFocus: true,
        	   		        	    enableKeyEvents: true,
        	   		        	    width: 200,
        	   		        	    listeners: {
        	   		            	    select: function(record) {
        	   		            	    	me.comboFieldSelected = this.value;
        	   		            	    },
        	   		            	    keypress: function(field, el)	{
        	   		            	    	if(el.getKey() == Ext.EventObject.ENTER)	{
        	   		                	    	me.comboFieldSelected = this.value;
        	   		                	    	me.search();
        	   		            	    	}
        	   		            	    }	           					
        	   		        	    }
        	   		    		}]
        				});         
        }
        
        var gridActions = Array();
        if (cfg.showAddRow)	{
        	gridActions.push({
        					xtype: 'button',
			                icon: 'images/add.png',
			                style: 'float:right',
			                tooltip: 'Add',
			                handler: function() {
								var newRecord = Ext.create(me.store.model);
								me.store.insert(0, newRecord);
		                        rowEditing.startEdit(newRecord, 0);
					     	}
        	});
        	cfg.rowEditing = true; // para poder guardar al hacer add
        }

        if (gridActions.length>0)	{
        	tbaritems.push( {
				xtype: 'panel',
				border: false,
				items: gridActions});
        }

        var tbarAux = null;
        if (tbaritems.length>0)	{
            tbarAux =  {
    				xtype: 'panel',
    				items: tbaritems};
        }
        
        var plugins = Array();

        if (cfg.cellEditing)	{        	
        	cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            	clicksToEdit: 2,
            	listeners: {
            		edit: function( editor, e, eOpts) {
						me.store.sync();
            		}
                 }            	
        	});
            plugins.push(rowEditing);
        }
        
        if (cfg.rowEditing)	{
            rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
            	clicksToEdit: 10, clicksToMoveEditor: 1, autoCancel: false,
            	listeners: {
                    edit: function( editor, e, eOpts) {
						me.store.sync();
                    }
                },            	
            });
            plugins.push(rowEditing);
        }

        
        
        me.callParent([Ext.apply({
			cls: 'grid',
    	    region:'center',
    	    framePanel: cfg.framePanel,
			store: cfg.store,
			columns: columnsAux,
			collapsible: false,
            loadMask: true,
            viewConfig: {
                stripeRows: true
            },
            plugins: plugins,
            listeners: {
                itemdblclick: function(sm, rowIndex, record) {
                	// no siempre hay framepanel, cuando es edit in line no hay
                	if (me.framePanel)	{
                    	me.framePanel.showDetail();
                    	me.framePanel.refreshDetail();
                	}
                }
            },

			tbar: tbarAux,

            bbar: Ext.createWidget('pagingtoolbar', {
            	store      : cfg.gridStore,
            	displayInfo: true,
            	displayMsg : 'Displaying topics {0} - {1} of {2}'
            })
        }, cfg)]);
    },

    search: function (field) {
    	this.store.clearFilter();
    	if (this.comboFieldSelected)	{
        	this.store.filter(this.comboFieldSelected, triggerFieldValue);
    	}
    	this.store.load();
	}
});
